package com.ruoyi.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.HhBrand;
import com.ruoyi.domain.HhProduct;
import com.ruoyi.domain.HhSize;
import com.ruoyi.domain.HhType;
import com.ruoyi.dto.SaleProductDto;
import com.ruoyi.mapper.*;
import com.ruoyi.service.IHhProductService;
import com.ruoyi.utils.ParamsDictUtil;
import com.ruoyi.utils.PingYinUtil;
import com.ruoyi.utils.PurchaseUtil;
import com.ruoyi.utils.SelectHelpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品信息Service业务层处理
 * @author chongjin
 * @date 2020-11-19
 */
@Service
public class HhProductServiceImpl implements IHhProductService {
    @Autowired
    private HhProductMapper hhProductMapper;
    @Autowired
    private HhTypeMapper hhTypeMapper;
    @Autowired
    private HhSizeMapper hhSizeMapper;
    @Autowired
    private HhBrandMapper hhBrandMapper;
    @Autowired
    private HhOrderDetailMapper hhOrderDetailMapper;

    /**
     * 查询商品信息
     * @param productId 商品信息ID
     * @return 商品信息
     */
    @Override
    public HhProduct selectHhProductById(Long productId) {
        HhProduct hhProduct = hhProductMapper.selectHhProductById(productId);
        if (StringUtils.isNotBlank(hhProduct.getProductImg())) {
            hhProduct.setProductImg(ParamsDictUtil.PRODUCT_PATH + "/" + hhProduct.getProductImg());
        }
        return hhProduct;
    }

    /**
     * 查询商品信息列表
     * @param hhProduct 商品信息
     * @return 商品信息
     */
    @Override
    public List<HhProduct> selectHhProductList(HhProduct hhProduct) {
        List<HhProduct> list = hhProductMapper.selectHhProductList(hhProduct);
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getProductImg())) {
                item.setProductImg(ParamsDictUtil.PRODUCT_PATH + "/" + item.getProductImg());
            }
            item.setPurchasePrice(PurchaseUtil.randomCode(item.getPurchasePrice()));
        });
        return list;
    }

    @Override
    public List<HhProduct> selectSaleHhProductList(SaleProductDto saleProductDto) {
        List<HhProduct> list = hhProductMapper.selectSaleHhProductList(saleProductDto);
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getProductImg())) {
                item.setProductImg(ParamsDictUtil.PRODUCT_PATH + "/" + item.getProductImg());
            }
            item.setPurchasePrice(PurchaseUtil.randomCode(item.getPurchasePrice()));
        });
        return list;
    }

    /**
     * 新增商品信息
     * @param hhProduct 商品信息
     * @return 结果
     */
    @Override
    public int insertHhProduct(HhProduct hhProduct) {
        hhProduct.setProductPrice(ParamsDictUtil.changePrice(hhProduct.getProductPrice()));
        hhProduct.setPurchasePrice(ParamsDictUtil.changePrice(hhProduct.getPurchasePrice()));
        hhProduct.setProductShortName(PingYinUtil.getFirstSpell(hhProduct.getProductName()));
        hhProduct.setCreateTime(DateUtils.getNowDate());
        return hhProductMapper.insertHhProduct(hhProduct);
    }

    /**
     * 初始查询商品参数
     * @param hhType 分类信息
     * @return 结果
     */
    @Override
    public Map selectProductInit(HhType hhType) {

        HhSize hhSize = new HhSize();
        hhSize.setTypeId(hhType.getTypeId());
        hhSize.setTypeParentId(hhType.getParentId());
        HhBrand hhBrand = new HhBrand();
        hhBrand.setTypeId(hhType.getTypeId());
        hhBrand.setTypeParentId(hhType.getParentId());

        List<HhType> typeList = hhTypeMapper.selectHhTypeList(hhType);
        List<HhSize> sizeList = hhSizeMapper.selectHhSizeList(hhSize);
        List<HhBrand> brandList = hhBrandMapper.selectHhBrandList(hhBrand);

        Map resultMap = new HashMap();
        resultMap.put("typeList", SelectHelpUtil.getNameType(typeList));
        resultMap.put("sizeList", SelectHelpUtil.getNameSize(sizeList));
        resultMap.put("brandList", SelectHelpUtil.getNameBrand(brandList));
        return resultMap;
    }

    /**
     * 修改商品信息
     * @param hhProduct 商品信息
     * @return 结果
     */
    @Override
    public int updateHhProduct(HhProduct hhProduct) {
        hhProduct.setProductPrice(ParamsDictUtil.changePrice(hhProduct.getProductPrice()));
        hhProduct.setPurchasePrice(ParamsDictUtil.changePrice(hhProduct.getPurchasePrice()));
        hhProduct.setProductShortName(PingYinUtil.getFirstSpell(hhProduct.getProductName()));
        hhProduct.setUpdateTime(DateUtils.getNowDate());
        return hhProductMapper.updateHhProduct(hhProduct);
    }

    /**
     * 删除商品信息对象
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteHhProductByIds(String ids) {
        String[] idss = Convert.toStrArray(ids);
        for (String id : idss) {
            //验证订单明细中是否存在该商品，存在则不允许删除
            if (hhOrderDetailMapper.productDeleteFlag(Long.parseLong(id)) > 0) {
                return 0;
            }
        }
        return hhProductMapper.deleteHhProductByIds(idss);
    }

    /**
     * 导入商品数据
     * @param productList     商品数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importProduct(List<HhProduct> productList, Boolean isUpdateSupport) {
        if (null == productList || productList.size() == 0) {
            throw new BusinessException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (HhProduct hhProduct : productList) {
            try {
                //查询拼装商品信息
                this.queryParamProduct(hhProduct);
                hhProduct.setCreateTime(DateUtils.getNowDate());
                successNum = successNum + hhProductMapper.insertHhProduct(hhProduct);
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品名【 " + hhProduct.getProductName() + "】异常信息：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败！共 " + failureNum + " 条，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    /**
     * 拼装导入商品信息
     */
    public void queryParamProduct(HhProduct hhProduct) {
        HhType hhType = hhTypeMapper.selectHhTypeByName(hhProduct.getProductType());
        if (null == hhType) {
            throw new BusinessException(ParamsDictUtil.IMPORT_NOT_TYPE);
        }
        hhProduct.setTypeId(hhType.getTypeId());
        hhProduct.setProductPrice(ParamsDictUtil.changePrice(hhProduct.getProductPrice()));
        hhProduct.setPurchasePrice(ParamsDictUtil.changePrice(hhProduct.getPurchasePrice()));
        hhProduct.setProductShortName(PingYinUtil.getFirstSpell(hhProduct.getProductName()));
        if (StringUtils.isNotBlank(hhProduct.getProductSize())) {
            HhSize hhSize = new HhSize();
            hhSize.setSizeName(hhProduct.getProductSize());
            hhSize.setTypeId(hhType.getTypeId());
            List<HhSize> result = hhSizeMapper.selectHhSizeList(hhSize);
            if (CollectionUtils.isNotEmpty(result)) {
                hhProduct.setSizeId(result.get(0).getSizeId());
            }
        }
        if (StringUtils.isNotBlank(hhProduct.getProductBrand())) {
            HhBrand hhBrand = new HhBrand();
            hhBrand.setBrandName(hhProduct.getProductBrand());
            hhBrand.setTypeId(hhType.getTypeId());
            List<HhBrand> result = hhBrandMapper.selectHhBrandList(hhBrand);
            if (CollectionUtils.isNotEmpty(result)) {
                hhProduct.setBrandId(result.get(0).getBrandId());
            }
        }
    }

}
